<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>4_生命周期(新)_getSnapshotBeforeUpdate使用场景</title>

    <style>
        .list {
            width: 200px;
            height: 150px;
            overflow: auto;
        }

        .news {
            height: 30px;
        }
    </style>

    <!-- 引入 react核心库 -->
    <script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
    <!-- 引入 react-dom 用于支持操作DOM -->
    <script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
    <!-- 引入 babel 用于将 jsx转为 js -->
    <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">

    class NewsList extends React.Component {

        state = {
            newsArr: []
        }

        componentDidMount() {
            setInterval(() => {
                const {newsArr} = this.state;
                const news = "新闻" + (newsArr.length + 1)
                // 更新状态
                this.setState({newsArr: [news, ...newsArr]});
            }, 1000)
        }

        getSnapshotBeforeUpdate() {
            return this.refs.list.scrollHeight;
        }

        componentDidUpdate(prevProps, prevState, height) {
            const listDom = this.refs.list;
            console.log(listDom.scrollHeight - height)
            listDom.scrollTop += listDom.scrollHeight - height;
        }

        render() {
            return (
                <div className="list" ref="list">
                    {
                        this.state.newsArr.map((n, index) => {
                            return <div key={index} className="news">{n}</div>
                        })
                    }
                </div>
            )
        }

    }

    ReactDOM.render(<NewsList/>, document.getElementById("test"));
</script>
</body>
</html>